import Toast from 'tdesign-miniprogram/toast/index';
// 接口
import { fetchShopDetail, fetchShopAddcart, fetchScoreshopDetail } from '~/request/api';

import { cdnBase } from '../../../config/index';

const imgPrefix = `${cdnBase}/`;

const recLeftImg = `${imgPrefix}common/rec-left.png`;
const recRightImg = `${imgPrefix}common/rec-right.png`;

Page({
  data: {
    detailInfo: {},
    recLeftImg,
    recRightImg,
    jumpArray: [
      {
        title: '首页',
        url: '/pages/home/home',
        iconName: 'home',
      },
      {
        title: '购物车',
        url: '/pages/cart/index',
        iconName: 'cart',
        // showCartNum: true,
      },
    ],
    isStock: true,
    buttonType: 1,
    buyNum: 1,
    isSpuSelectPopupShow: false,
    buyType: 0,
    outOperateStatus: false, // 是否外层加入购物车
    goods_id: null,
    navigation: { type: 'fraction' },
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    isValidityLinePrice: false,
    symbol: '¥'
  },

  handlePopupHide() {
    this.setData({
      isSpuSelectPopupShow: false,
      buyNum: 1,
    });
  },

  showSkuSelectPopup(type) {
    this.setData({
      buyType: type || 0,
      outOperateStatus: type >= 1,
      isSpuSelectPopupShow: true,
    });
  },

  // 添加购物车 | 立即购买弹窗确定回调
  specsConfirm() {
    const { buyType } = this.data;
    if (buyType === 1) {
      this.gotoBuy();
    } else {
      this.addCart();
    }
  },

  buyItNow() {
    this.showSkuSelectPopup(1);
  },

  toAddCart() {
    this.showSkuSelectPopup(2);
  },

  toNav(e) {
    const { url } = e.detail;
    if (url === '/pages/cart/index') {
      wx.navigateTo({
        url
      })
    } else {
      wx.switchTab({
        url,
      });
    }
  },

  showCurImg(e) {
    const { index } = e.detail;
    const { images } = this.data.details;
    wx.previewImage({
      current: images[index],
      urls: images, // 需要预览的图片http链接列表
    });
  },

  changeNum(e) {
    this.setData({
      buyNum: e.detail.buyNum,
    });
  },

  onPageScroll({ scrollTop }) {
    const goodsTab = this.selectComponent('#goodsTab');
    goodsTab && goodsTab.onScroll(scrollTop);
  },

  // 添加购物车
  async shopAddcart(params) {
    try {
      const res = await fetchShopAddcart(params);
      Toast({
        context: this,
        selector: '#t-toast',
        message: res.msg,
        icon: '',
        duration: 1000,
      });
      return res.data?.cart_id;
    } catch (error) {
      console.log(error);
    }
    return '';
  },

  addCart() {
    const { goods_id, buyNum } = this.data;
    if (buyNum == 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '数量不能为0！',
        icon: '',
        duration: 1000,
      });
      return;
    }
    this.shopAddcart({ goods_id, num: buyNum });
    // 关闭弹窗
    this.handlePopupHide();
  },

  // 立即购买
  async gotoBuy() {
    const { goods_id, buyNum } = this.data;
    if (buyNum == 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '数量不能为0！',
        icon: '',
        duration: 1000,
      });
      return;
    }
    const cart_id = await this.shopAddcart({ goods_id, num: buyNum });
    this.handlePopupHide();
    wx.navigateTo({ url: `/pages/order/order-confirm/index?cart_ids=${cart_id}` });
  },

  // 获取商品详情
  async getDetail(goods_id) {
    try {
      const res = await fetchShopDetail({ goods_id });
      let _images = res?.images?.split('|');
      // 是否显示原价格
      let isValidityLinePrice = true;
      if (res.market_price && res.sale_price && +res.market_price <= +res.sale_price) {
        isValidityLinePrice = false;
      }
      this.setData({ detailInfo: { ...res, images: _images }, isValidityLinePrice });
    } catch (error) {
      console.log(error);
    }
  },

  // 积分商品详情
  async getScoreDetail(goods_id) {
    try {
      const res = await fetchScoreshopDetail({ goods_id });
      let _images = res?.images?.split('|');
      // 是否显示原价格
      let isValidityLinePrice = false;
      this.setData({ detailInfo: { ...res, images: _images }, isValidityLinePrice, symbol: '' });
    } catch (error) {
      console.log(error);
    }
  },

  // 立即兑换
  async buyInteral() {
    const { goods_id, buyNum } = this.data;
    if (buyNum == 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '数量不能为0！',
        icon: '',
        duration: 1000,
      });
      return;
    }
    // this.handlePopupHide();
    wx.navigateTo({ url: `/pages/order/order-confirm/index?goods_id=${goods_id}` });
  },

  onLoad(query) {
    const { goods_id, type } = query;
    this.setData({
      goods_id,
      detailType: type
    });
    if (type && type === 'integral') {
      this.getScoreDetail(goods_id)
    } else {
      this.getDetail(goods_id);
    }
  },
});
